package leveup.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * JIT优化——锁粗化
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/31 下午 05:47
 */
public class LockCoarsening {
    final static Object obj = new Object();

    /**
     * 连续对同个对象进行同步操作，JIT会将锁组化，等价于fun2()方法
     */
    public static void fun(){
        synchronized (obj){
            System.out.println(1);
        }
        synchronized (obj){
            System.out.println(2);
        }
        synchronized (obj){
            System.out.println(3);
        }
        synchronized (obj){
            System.out.println(4);
        }
        synchronized (obj){
            System.out.println(5);
        }
    }


    public static void fun2(){
        synchronized (obj){
            System.out.println(1);
            System.out.println(2);
            System.out.println(3);
            System.out.println(4);
            System.out.println(5);
        }
    }

    public static void main(String[] args) throws Exception {

        ExecutorService threadPool = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            threadPool.submit(()->{
                fun();
            });
        }
        Thread.sleep(1000);
        threadPool.shutdown();

    }

}
